const { Configuration, OpenAIApi } = require('openai');
const configuration = new Configuration({
  apiKey: process.env.OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);

const { getReplys } = require('../dbs/replys');

// 订阅回复的消息消息
function subscribeMsg(toUser, fromUser, timestamp) {
  const text = `欢迎来到Code工场，专注于开展科普教育、少儿编程、人工智能及信奥赛升学规划等服务。

☕️ 回复【专题】，即可获取<a href="https://mp.weixin.qq.com/s?__biz=MzIzMjY0NjU5Ng==&mid=2247487946&idx=1&sn=1109f03b81a7bc4992a23461e0b3032e&chksm=e890e361dfe76a7747016b79c1c61edacd63600b3c3ed7eb23f53138e8ccff2edf3f4127e45c#rd">《Scratch专题精品课程》</a>。

☕️ 回复【逻辑思维】，免费获取<a href="https://mp.weixin.qq.com/s?__biz=MzIzMjY0NjU5Ng==&mid=2247486742&idx=1&sn=755087077fe3c9dfddc049d1f76011a8&chksm=e890ffbddfe776abbb1e87fea01b47e910e596220c0fc15225bb0aeda4bbbeea5f05752072ef#rd">《逻辑思维100题》</a>系列文章题解。

☕️ 回复【安装包】，免费获取<a href="https://mp.weixin.qq.com/s?__biz=MzIzMjY0NjU5Ng==&mid=2247486954&idx=1&sn=caa613eb62f0a9d3a54a88ae3cca4dec&chksm=e890ff41dfe7765701496c00d4dee2e5e27ed0073bf5926f90882445d65469a46c60a342df1c#rd">Scratch安装包（Windows版本和苹果版本）</a>。

Stay Hungry. Stay Foolish. 永远保持一颗求知的心！

记得点头像图标 → 点右上角“...” → 点“设为星标 ★ ”，就不会错过更新啦。`;
  return `<xml>
<ToUserName><![CDATA[${toUser}]]></ToUserName>
<FromUserName><![CDATA[${fromUser}]]></FromUserName>
<CreateTime>${timestamp}</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[${text}]]></Content>
</xml>`;
}

// 添加客服微信回复
function contactUSMsg(toUser, fromUser, timestamp) {
  // 回复二维码图片
  const mediaId = process.env.WECHAT_QR_MEDIAID;
  return `<xml><ToUserName><![CDATA[${toUser}]]></ToUserName><FromUserName><![CDATA[${fromUser}]]></FromUserName><CreateTime>${timestamp}</CreateTime><MsgType><![CDATA[image]]></MsgType><Image><MediaId><![CDATA[${mediaId}]]></MediaId></Image></xml>`;
}

// 关键词回复
function keywordsMsg(toUser, fromUser, timestamp, keyword) {
  // 获取关键词相关的回复
  let replys = getReplys(keyword);
  if (replys.length == 1) {
    return `<xml><ToUserName><![CDATA[${toUser}]]></ToUserName><FromUserName><![CDATA[${fromUser}]]></FromUserName><CreateTime>${timestamp}</CreateTime><MsgType><![CDATA[news]]></MsgType><ArticleCount>1</ArticleCount><Articles><item><Title><![CDATA[${replys[0]['title']}]]></Title><Description><![CDATA[${replys[0]['description']}]]></Description><PicUrl><![CDATA[${replys[0]['coverUrl']}]]></PicUrl><Url><![CDATA[${replys[0]['articleUrl']}]]></Url></item></Articles></xml>`;
  }
  if (replys.length > 1) {
    let list = ['AI机器人为您找到相关文章：'];
    for (let i = 0; i < replys.length; i++) {
      list.push(
        `<a href="${replys[i]['articleUrl']}">${i + 1}.《${replys[i]['title']
        }》</a>`
      );
    }
    list.push('\r\n👆点击文章标题，即可访问！');
    return `<xml>
<ToUserName><![CDATA[${toUser}]]></ToUserName>
<FromUserName><![CDATA[${fromUser}]]></FromUserName>
<CreateTime>${timestamp}</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[${list.join('\r\n')}]]></Content>
</xml>`;
  } else {
    return '';
  }
}

// ChatGPT回复
async function chatGPTMsg(toUser, fromUser, timestamp, question) {
  let text = '';
  if (question.length > 100) {
    text = '对不起，你的问题太长了，我现在还小，暂时无法理解！';
  } else {
    const response = await openai.createCompletion({
      model: 'text-davinci-003', // 使用的模型，固定值text-davinci-003
      prompt: question, // 你的问题
      temperature: 0, // 0~2之间
      max_tokens: 2048, // 答案的最大字符数
    });
    text =
      response.data &&
      response.data.choices[0] &&
      response.data.choices[0].text;
    if (text.startsWith('\n\n')) text = text.slice(2);
  }

  return `<xml>
<ToUserName><![CDATA[${toUser}]]></ToUserName>
<FromUserName><![CDATA[${fromUser}]]></FromUserName>
<CreateTime>${timestamp}</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[${text}]]></Content>
</xml>`;
}

/**
 *
 * @param {String} fromUserName 发送消息用户
 * @param {String} toUserName 接收账号
 * @param {String} timestamp 时间戳
 * @param {String} event 事件类型
 * @param {String} msgType 消息类型
 * @param {String} content 消息内容
 */
async function generateMessage({
  fromUserName,
  toUserName,
  timestamp,
  msgType,
  event,
  content,
}) {
  let plain = '';
  if (msgType === 'text' && content) {
    // 关键词回复
    plain = keywordsMsg(fromUserName, toUserName, timestamp, content);
  } else if (msgType === 'event' && event === 'subscribe') {
    // 订阅消息回复
    plain = subscribeMsg(fromUserName, toUserName, timestamp);
  }
  // 如果没有回复内容则返回添加微信
  if (!plain || plain == '') {
    // 回复联系我们
    plain = contactUSMsg(fromUserName, toUserName, timestamp);
  }
  return plain;
}

module.exports = {
  generateMessage,
};
